 import requests
import random
import time
from datetime import datetime
import json
import threading
from faker import Faker

# 配置
BASE_URL = 'http://localhost:5000'
fake = Faker(['zh_CN'])  # 使用中文名称

# 模拟用户数据池
users = []
for i in range(100):
    users.append({
        'username': fake.user_name(),
        'password': 'password123',  # 统一密码便于测试
        'email': fake.email(),
        'is_admin': random.random() < 0.1  # 10%概率是管理员
    })

def simulate_user_activity():
    """模拟用户活动"""
    while True:
        try:
            # 随机选择一个操作
            action = random.choice(['register', 'login', 'logout'])
            
            if action == 'register':
                # 注册新用户
                new_user = {
                    'username': fake.user_name(),
                    'password': 'password123',
                    'email': fake.email(),
                    'is_admin': random.random() < 0.1
                }
                response = requests.post(f'{BASE_URL}/register', json=new_user)
                if response.status_code == 201:
                    users.append(new_user)
                    print(f"新用户注册成功: {new_user['username']}")
                
            elif action == 'login':
                # 随机选择一个已有用户登录
                user = random.choice(users)
                response = requests.post(f'{BASE_URL}/login', json={
                    'username': user['username'],
                    'password': user['password'],
                    'userType': 'admin' if user['is_admin'] else 'user'
                })
                if response.status_code == 200:
                    print(f"用户登录成功: {user['username']}")
                
            elif action == 'logout':
                # 模拟登出（实际不需要调用API）
                if users:
                    user = random.choice(users)
                    print(f"用户登出: {user['username']}")
            
            # 随机等待1-5秒
            time.sleep(random.uniform(1, 5))
            
        except Exception as e:
            print(f"Error: {str(e)}")
            time.sleep(5)  # 出错后等待5秒再继续

def simulate_multiple_users(num_threads=3):
    """启动多个线程模拟多用户活动"""
    threads = []
    for _ in range(num_threads):
        thread = threading.Thread(target=simulate_user_activity)
        thread.daemon = True
        thread.start()
        threads.append(thread)
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n停止模拟...")

if __name__ == '__main__':
    print("开始模拟用户活动...")
    print(f"初始用户池大小: {len(users)}")
    simulate_multiple_users()